package com.xjtu.service;


import com.xjtu.common.constant.Chat;
import com.xjtu.repository.ChatRepository;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * 聊天服务
 */
@Service
public class ChatService {
    @Resource
    private ChatRepository chatRepository;


    //登录
    public boolean login(String username, String password) {
        return true;
    }


    //按时间降序后返回前30（最大）条聊天记录
    public List<com.xjtu.model.Chat> getChatRecord(String id1, String id2, Integer limit) {
        if (Objects.isNull(limit)) {
            limit = Chat.DEFAULT_RECORD_SIZE;
        } else {
            limit = Math.min(limit, Chat.DEFAULT_RECORD_SIZE);
        }
        Query query = new Query(new Criteria().orOperator(
                new Criteria().andOperator(Criteria.where("from").is(id1), Criteria.where("to").is(id2)),
                new Criteria().andOperator(Criteria.where("from").is(id2), Criteria.where("to").is(id1))))
                .with(Sort.by(Sort.Order.desc("time")));
        List<com.xjtu.model.Chat> chats = chatRepository.find(query);
        return chats.subList(0, Math.min(limit, chats.size()));
    }

    //获取某用户所有聊天记录
    public Map<String, List<com.xjtu.model.Chat>> getAllChatRecord(String id) {
        Map<String, List<com.xjtu.model.Chat>> map = new HashMap<>();

        Query query = new Query(new Criteria().orOperator(
                Criteria.where("from").is(id), Criteria.where("to").is(id)))
                .with(Sort.by(Sort.Order.desc("time")));
        List<com.xjtu.model.Chat> chatList = chatRepository.find(query);
        for (com.xjtu.model.Chat chat : chatList) {
            String with = chat.getFrom().equals(id) ? chat.getTo() : chat.getFrom();
            map.computeIfAbsent(with, k -> new ArrayList<>());
            //和每个用户的聊天记录最多显示30条最新
            if (map.get(with).size() < Chat.DEFAULT_RECORD_SIZE) {
                map.get(with).add(chat);
            }
        }
        return map;
    }


    public void addChatRecord(String text) {
        String from = new Random().nextInt() + "";
        com.xjtu.model.Chat chat = new com.xjtu.model.Chat(from, "2", text);
        chatRepository.save(chat);
    }

}
